//
//  tagView.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/9.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//
// 标签

import UIKit

class TagView: UIView {
    private let buttonMargin: CGFloat = 10
    private let buttonTBMargin: CGFloat = 12
    var tapClouser:((String) -> Void)?
    override func awakeFromNib() {
        
    }
    
    func showData(titles: [String], buttnLROffset: CGFloat, tapClouser:@escaping (String) -> Void) -> CGFloat? {
        if self.subviews.count > 1 {
            return nil
        }
        self.tapClouser = tapClouser
        self.layoutIfNeeded()
        var beforButton: UIButton?
        var buttonHeight: CGFloat = 0
        var row: CGFloat = 0
        for title in titles {
            let button = UIButton(type: .system)
            button.setTitle(title, for: .normal)
            button.setTitleColor(UIColor.black, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.backgroundColor = UIColor(hex: 0xF5F5F5)
            button.sizeToFit()
            button.width += buttnLROffset
            var xPoint: CGFloat = 0
            if let beforButton = beforButton {
                if self.width < (beforButton.right + buttonMargin + button.width) {
                    row += 1
                } else {
                    xPoint = beforButton.right + buttonMargin
                }
            }
            
            button.frame = CGRect(x: xPoint, y: row * button.height + row * buttonTBMargin, width: button.width, height: button.height)
            button.layer.cornerRadius = button.height / 2
            button.addTarget(self, action: #selector(tagTap(_ :)), for: .touchUpInside)
            self.addSubview(button)
            buttonHeight = button.height
            beforButton = button
        }
        
        return row  * buttonTBMargin + buttonHeight * (row + 1)
    }
    
    @objc func tagTap(_ btn: UIButton) {
        self.tapClouser?(btn.currentTitle ?? "")
    }
    
}
